package com.le.buddha.common.cosyvoice;

import cn.hutool.core.io.FileUtil;
import com.alibaba.nls.client.AccessToken;
import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.OutputFormatEnum;
import com.alibaba.nls.client.protocol.SampleRateEnum;
import com.alibaba.nls.client.protocol.tts.StreamInputTts;
import com.alibaba.nls.client.protocol.tts.StreamInputTtsListener;
import com.alibaba.nls.client.protocol.tts.StreamInputTtsResponse;

import java.nio.ByteBuffer;

/**
 * @author guole
 * @created 2024/10/4
 */
public class GuoleCosyVoiceDemo {

    public    byte[] textToSpeech(String text,String voiceName){
         StreamInputTts synthesizer=null;
        GuoleCosyVoiceB b=new GuoleCosyVoiceB();
        byte[] speechByte=null;
        try {
            AccessToken accessToken = new AccessToken("LTAI5t6rV2sRnzL5p1WpAQse", "lqns8N8N7C4FqGYniJbC5ERHrIM0hx");
            accessToken.apply();
            String token = accessToken.getToken();
            String url = "wss://nls-gateway-cn-beijing.aliyuncs.com/ws/v1";
            String appKey = "sMvM7FonodPcw708";

            NlsClient client = new NlsClient(url, token);
              synthesizer = new StreamInputTts(client,getSynthesizerListener(b) );
            synthesizer.setAppKey(appKey);
            //设置返回音频的编码格式。
            synthesizer.setFormat(OutputFormatEnum.MP3);
            //设置返回音频的采样率。
            synthesizer.setSampleRate(SampleRateEnum.SAMPLE_RATE_24K);
            synthesizer.setVoice(voiceName);
            //音量，范围是0~100，可选，默认50。
            synthesizer.setVolume(50);
            //语调，范围是-500~500，可选，默认是0。
            synthesizer.setPitchRate(0);
            //语速，范围是-500~500，默认是0。
            synthesizer.setSpeechRate(0);
            //此方法将以上参数设置序列化为JSON发送给服务端，并等待服务端确认。
            long start = System.currentTimeMillis();
            synthesizer.startStreamInputTts();
            System.out.println("tts start latency " + (System.currentTimeMillis() - start) + " ms");

                 //发送流式文本数据。
                synthesizer.sendStreamInputTts(text);
            //通知服务端流式文本数据发送完毕，阻塞等待服务端处理完成
            synthesizer.stopStreamInputTts();
             speechByte=  b.getSpeechByte();

        } catch (Exception e) {
             e.printStackTrace();
        }finally {
            if (null != synthesizer) {
                synthesizer.close();
             }
        }


        return  speechByte;
     }
    private   StreamInputTtsListener getSynthesizerListener(GuoleCosyVoiceB b){
        StreamInputTtsListener listener = null;
        try {
            listener = new StreamInputTtsListener() {


                private boolean firstRecvBinary = true;

                //流式文本语音合成开始
                @Override
                public void onSynthesisStart(StreamInputTtsResponse response) {
                    System.out.println("name: " + response.getName() +
                            ", status: " + response.getStatus());
                }

                //服务端检测到了一句话的开始
                @Override
                public void onSentenceBegin(StreamInputTtsResponse response) {
                    System.out.println("name: " + response.getName() +
                            ", status: " + response.getStatus());
                    System.out.println("Sentence Begin");
                }

                //服务端检测到了一句话的结束，获得这句话的起止位置和所有时间戳
                @Override
                public void onSentenceEnd(StreamInputTtsResponse response) {
                    System.out.println("name: " + response.getName() +
                            ", status: " + response.getStatus() + ", subtitles: " + response.getObject("subtitles"));

                }

                //流式文本语音合成结束
                @Override
                public void onSynthesisComplete(StreamInputTtsResponse response) {
                    // 调用onSynthesisComplete时，表示所有TTS数据已经接收完成，所有文本都已经合成音频并返回。
                   //  audioPlayer.stop();
                }

                //收到语音合成的语音二进制数据
                @Override
                public void onAudioData(ByteBuffer message) {
                    b.addByte(message);
                }

                //收到语音合成的增量音频时间戳
                @Override
                public void onSentenceSynthesis(StreamInputTtsResponse response) {

                }

                @Override
                public void onFail(StreamInputTtsResponse response) {
                    // task_id是调用方和服务端通信的唯一标识，当遇到问题时，需要提供此task_id以便排查。
                    System.out.println(
                            "session_id: " + getStreamInputTts().getCurrentSessionId() +
                                    ", task_id: " + response.getTaskId() +
                                    //状态码
                                    ", status: " + response.getStatus() +
                                    //错误信息
                                    ", status_text: " + response.getStatusText());
                   // audioPlayer.stop();
                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listener;
    }

    public static void main(String[] args) {
        GuoleCosyVoiceDemo guoleCosyVoiceDemo=new GuoleCosyVoiceDemo();
      // byte[] result= guoleCosyVoiceDemo.textToSpeech("我叫郭乐，我是最牛逼的人");
     //   FileUtil.writeBytes(result,"d:/22.mp3");

    }
}
